<template>
	<div class="processDrawBody">
		<div class="containerBox" style="position: relative;">
			<div id="container">
				<el-button-group>
					<el-button size="mini" @click="showProcessInfo">编辑组合流程</el-button>
					<el-button type="primary" size="mini" @click="handleUndo">撤销</el-button>
					<el-button type="success" size="mini" @click="handleRedo">恢复</el-button>
					<el-button type="warning" size="mini" @click="handleDownload">下载</el-button>
					<el-button color="#626aef" @click="onAffirm">确认创建</el-button>
					<el-upload style="display: inline-block;" :file-list="fileList" class="upload-demo" action=""
						:auto-upload="false" :show-file-list="false" :http-request="httpRequest"
						:on-change="handleOnchangeFile" :on-remove="handleRemove" :before-remove="beforeRemove">
						<el-button type="danger" size="mini">导入</el-button>
					</el-upload>

				</el-button-group>
			</div>
			<div id="js-properties-panel" class="panel"></div>
		</div>
	</div>
	<el-dialog v-model="dialogFormVisible" title="服务信息">
		<el-form :model="form" label-width="120px" style="width: 60%;">
			<el-form-item label="服务名称">
				<el-input v-model="form.name" />
			</el-form-item>
			<el-form-item label="服务描述">
				<el-input v-model="form.desc" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogFormVisible = false">Cancel</el-button>
				<el-button type="primary" @click="onSubmit">
					Confirm
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script>
import { markRaw } from 'vue';
// bpmn-js相关
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
import BpmnModeler from 'bpmn-js/lib/Modeler';
// bpmn-js-properties-panel相关
import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css'
import propertiesPanelModule from 'bpmn-js-properties-panel'
// 自定义属性面板
import propertiesProviderModule from './bpmn/provider/authority';
import authorityModdleDescriptor from './bpmn/descriptors/camunda'
import customTranslate from './bpmn/Translate/customTranslate';

import Api from '../util/axios';
import { Success } from '../util/message';

export default {
	props: ['deploymentId'],
	data() {
		return {
			containerEl: null,
			bpmnModeler: null,
			fileList: [],
			dialogFormVisible: false,
			form: { name: '', desc: '' }
		};
	},
	mounted() {
		// 初始化流程图
		this.init();
	},
	methods: {
		/**
		 * 初始化流程图
		 */
		init() {
			this.containerEl = document.getElementById('container');
			//将汉化包装成一个模块
			const customTranslateModule = {
				translate: ["value", customTranslate],
			};
			// 加markRaw去除双向绑定作用域
			this.bpmnModeler = markRaw(new BpmnModeler({
				container: this.containerEl,
				// 添加控制板
				propertiesPanel: {
					parent: '#js-properties-panel',
					// propertiesProvider: new BpmnPropertiesProvider({
					// 	properties: [
					// 		{
					// 			id: 'myProperty',
					// 			label: 'My Property',
					// 			type: 'string',
					// 			defaultValue: 'default value'
					// 		}
					// 	]
					// })
				},
				// 右侧属性面板
				additionalModules: [
					propertiesPanelModule,
					propertiesProviderModule,
					customTranslateModule
				],
				moddleExtensions: {
					authority: authorityModdleDescriptor
				}
			}));
			this.bpmnModeler.createDiagram(() => {
				this.bpmnModeler.get('canvas').zoom('fit-viewport');
			});
			let _this = this;
			if (_this.deploymentId) {
				Api.post('queryDeploymentByName', {
					"deploymentName": _this.deploymentId + '.bpmn'
				}).then((res) => {
					_this.form.name = _this.deploymentId
					_this.form.desc = res.description
					_this.bpmnModeler.importXML(this.activiti2camunda(res.content), (err) => {
						this.$message.success('加载成功！');
					});
				})
			}
		},
		handleRemove(file) {
			for (let i = 0; i < this.fileList.length; i++) {
				if (file.name === this.fileList[i].name) {
					this.fileList.splice(i, 1);
				}
			}
		},
		beforeRemove(file) {
			return this.$confirm(`确定移除 ${file.name}？`);
		},
		// 后退
		handleUndo() {
			this.bpmnModeler.get('commandStack').undo();
		},
		// 前进
		handleRedo() {
			this.bpmnModeler.get('commandStack').redo();
		},
		// 下载
		async handleDownload() {
			this.bpmnModeler.saveXML({ format: true }, (err, data) => {
				const dataTrack = 'bpmn';
				const a = document.createElement('a');
				const name = `diagram.${dataTrack}`;
				a.setAttribute(
					'href',
					`data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(this.camunda2activiti(data))}`
				);
				a.setAttribute('target', '_blank');
				a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
				a.setAttribute('download', name);
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
			});
		},
		// 导入成功回调
		handleOnchangeFile(file) {
			const reader = new FileReader();
			let data = '';
			reader.readAsText(file.raw);
			reader.onload = (event) => {
				data = this.activiti2camunda(event.target.result);
				console.log(data);
				this.bpmnModeler.importXML(data, (err) => {
					if (err) {
						this.$message.info('导入失败');
					} else {
						this.$message.success('导入成功');
					}
				});
			};
		},
		// 取xml信息
		showProcessInfo() {
			this.bpmnModeler.saveXML({ format: true }, (err, data) => {
				// alert(data);
				console.log(data);
			});
		},
		/**
		 * 保存
		 */
		save() {
			this.bpmnModeler.saveXML({ format: true }, (err, data) => {
				let processInfo = {};
				processInfo.xml = data.replace(/camunda/ig, "activiti");
				processInfo.processId = document.getElementById("camunda-id").value;
				processInfo.processName = document.getElementById("camunda-name").innerHTML;
				// processDeployment(processInfo)
				// 	.then((res) => {
				// 		console.log(res);
				// 	})
				// 	.catch((error) => {
				// 		console.log(error);
				// 	});
			});
		},
		camunda2activiti(data) {
			let head = '<?xml version="1.0" encoding="UTF-8"?>'
			return data.replace(/camunda.org\/schema\/1.0/ig, "activiti.org").replace(/camunda/ig, "activiti").substring(head.length);
		},
		activiti2camunda(data) {
			let head = '<?xml version="1.0" encoding="UTF-8"?>'
			return (data.substr(0, 5) == '<?xml' ? '' : head) + data.replace(/activiti.org/ig, "camunda.org/schema/1.0").replace(/activiti/ig, "camunda");
		},
		onAffirm() {
			this.dialogFormVisible = true
		},
		async onSubmit() {
			let svg
			await this.bpmnModeler.saveSVG({ format: true }, (err, data) => {
				svg = this.camunda2activiti(data)
			})
			this.bpmnModeler.saveXML({ format: true }, (err, data) => {
				Api.post('deploy', { deploymentName: this.form.name + '.bpmn', description: this.form.desc, svg: svg, fileContent: this.camunda2activiti(data) }).then((res) => {
					this.$router.push({ name: 'list' });
					Success('保存成功'); 2
				})
			})
		}
	}
}
</script>
<style>
.processDrawBody {
	height: 95%;
	text-align: left;
}

.containerBox {
	height: 100%;
}

.containerBox #container {
	height: 100%;
	border: 1px solid rgb(121, 121, 121);
}

.bpp-properties-panel [type=text] {
	box-sizing: border-box;
}

.panel {
	width: 30%;
	position: absolute;
	top: 1px;
	right: 1px;
	height: 100%;
	overflow: auto;
}

/* 右下角logo */
.bjs-powered-by {
	display: none;
}
</style>
